package com.sdonkey.score.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zc on 2017/01/03 0003.
 */
public class CustomerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        ModelAndView mv = new ModelAndView();
        CodeMessage cm;

//        StackTraceElement[] stackTrace = e.getStackTrace();
//        System.out.println(stackTrace[0].getFileName() + " : " + stackTrace[0].getMethodName() + " : " + stackTrace[0].getLineNumber());

        if (e instanceof RuntimeException) {
            cm = new CodeMessage(CustomerException.SERVER_ERROR.getCode(), "运行时异常 ==> " + e.getMessage());
        } else if (e instanceof CustomerException) {
            cm = new CodeMessage(((CustomerException) e).getCode(), e.getMessage());
        } else {
            cm = new CodeMessage(CustomerException.SERVER_ERROR.getCode(), e.toString());
        }
        mv.addObject("exception", cm);
        mv.addObject("resultCode", cm.getCode());
        mv.addObject("resultMessage", "未知错误");
        mv.setViewName("error");
        System.out.println("出现异常：       异常码：" + cm.getCode() + "     异常方法：" + e.getStackTrace()[1].getMethodName() + "      异常信息：" + cm.getMessage());

//        HandlerMethod handlerMethod = (HandlerMethod) handler;
//        ResponseBody body = handlerMethod.getMethodAnnotation(ResponseBody.class);
//        if (body != null) { //针对应该返回json数据的方法
//            try {
//                //返回json数据
//                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
//                response.setCharacterEncoding("UTF-8");
//                response.setHeader("Cache-Control", "no-cache, must-revalidate");
//                PrintWriter writer = response.getWriter();
//                Map<String, Object> errMap = new HashMap<>();
//                errMap.put("errCode", cm.getCode());
//                errMap.put("errMsg", cm.getMessage());
//                writer.write(JSONObject.valueToString(errMap));
//                writer.close();
//            } catch (IOException e1) {
//                e1.printStackTrace();
//            }
//        }
        return mv;
    }

}
